package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.mapper.OrderDetailMapper;
import com.bwie.mapper.OrderRecordMapper;
import com.bwie.mapper.ProdInfoMapper;
import com.bwie.poi.ExcelUtil;
import com.bwie.pojo.OrderDetail;
import com.bwie.pojo.OrderRecord;
import com.bwie.pojo.ProdInfo;
import com.bwie.utils.R;
import com.bwie.utils.TokenUtil;
import com.bwie.vo.PageInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.OrderMapper;
import com.bwie.pojo.Order;
import com.bwie.service.OrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: 鑫仔
 * @Date: 2025/7/23 18:49
 * @Description:
 **/

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProdInfoMapper prodInfoMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;


    @Autowired
    private OrderRecordMapper orderRecordMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;


    @Override
    public R getOrderList(PageInfoVo pageInfoVo) {

        String token = request.getHeader("token");
        Integer userId = TokenUtil.getUserId(token);

        Page<Order> orderPage = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        Page<Order> page = orderMapper.getOrderList(orderPage, pageInfoVo);

        String key = "order-list-" + userId;
        redisTemplate.opsForValue().set(key, JSON.toJSONString(page.getRecords()), 60, TimeUnit.MINUTES);
        return R.OK(page);
    }

    @Override
    public void exportOrder(Integer userId) {
        ExcelUtil<Order> excelUtil = new ExcelUtil<>(Order.class);
        String key = "order-list-" + userId;
        String redisKey = redisTemplate.opsForValue().get(key);
        List<Order> orderList = JSON.parseArray(redisKey, Order.class);

        excelUtil.exportExcel(response, orderList, "订单列表");

    }

    @Override
    public R deleteBatchOrder(List<Integer> ids) {
        orderMapper.deleteBatchIds(ids);
        log.info("删除成功");
        return R.OK();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R addOrder(List<ProdInfo> prodInfo) {
        String token = request.getHeader("token");
        String userName = TokenUtil.getUserName(token);
        Integer userId = TokenUtil.getUserId(token);

        BigDecimal totalAmount = new BigDecimal("0");
        StringBuilder name = new StringBuilder();


        for (ProdInfo info : prodInfo) {
            ProdInfo pInfo = prodInfoMapper.selectById(info.getInfoId());
            log.info("信息数据" + pInfo);
            if (info.getNum() > pInfo.getProdStock()) {
                log.info("库存不足");
                throw new RuntimeException("库存不足");
            }
            pInfo.setProdStock(pInfo.getProdStock() - info.getNum());
            prodInfoMapper.updateById(pInfo);

            totalAmount = totalAmount.add(info.getProdPrice()).multiply(new BigDecimal(info.getNum()));

            if (name.length() > 0) {
                name.append(",");
                name.append(info.getProdName());
            } else {
                name.append(info.getProdName());
            }
        }

        Order order = new Order();
        long code = IdUtil.createSnowflake(1, 1).nextId();
        order.setOrderNo("" + code);
        order.setOrderStatus(1);
        order.setOrderType(1);
        order.setUserId(userId);
        order.setCreateBy(userName);
        order.setCreateTime(new Date());
        order.setOrderAmount(totalAmount);
        order.setProdInfo(name.toString());

        orderMapper.insert(order);


        for (ProdInfo info : prodInfo) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setInfoId(info.getInfoId());
            orderDetail.setOrderId(order.getOrderId());
            orderDetail.setProdId(info.getProdId());
            orderDetail.setBuyNum(info.getNum());
            orderDetail.setBuyPrice(info.getCostPrice());

            orderDetail.setCreateBy(userName);
            orderDetail.setCreateTime(new Date());
            orderDetailMapper.insert(orderDetail);

        }

        OrderRecord orderRecord = new OrderRecord();
        orderRecord.setOrderId(order.getOrderId());
        orderRecord.setOptRecord("用户创建订单");
        orderRecord.setCreateBy(userName);
        orderRecord.setCreateTime(new Date());
        orderRecordMapper.insert(orderRecord);

        return R.OK();
    }
}
